package net.tngou.crawler.drug.license;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import net.tngou.c4j.util.HttpUtil;
import net.tngou.cache.CacheEngine;
import net.tngou.cache.TgCacheEngine;
import net.tngou.crawler.jdbc.DBManager;
import net.tngou.crawler.pojo.License;
import net.tngou.crawler.pojo.POJO;
import net.tngou.crawler.util.StringUtil;

public class CN_GOV_CFDA {
	public static Long getId(String engines)
	{
		CacheEngine engine = new TgCacheEngine();//创建缓存    
		 Long id=(Long) engine.get(engines);
		 id=id==null?1:id;
//		 id=65535L;
		 engine.add(engines,  id+1);//存在  默认的储存库为 default
		 return id;	 
	}
	public static JSONObject getData(int table,long id) {
		String url="http://mobile.cfda.gov.cn/datasearch/QueryRecord?tableId="+table+"&searchF=ID&searchK="+id;
		String doc = HttpUtil.getString(url);
		if(doc==null) return null;
		try {
			if(doc.startsWith("[")) {
				JSONArray arrays = JSON.parseArray(doc);
				
				JSONObject rjson=new JSONObject();
				for (Object object : arrays) {
					JSONObject json =(JSONObject) object;
					rjson.put(StringUtil.cleanKey(json.getString("NAME")), StringUtil.RemoveEmpty(json.getString("CONTENT")));
					
				}
				rjson.remove("注");
				rjson.remove("相关数据库查询");
				return rjson;
			}
			return getData(table,id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void save(License license) {
		if(StringUtil.isNotEmpty(license.getName())) {
			POJO pojo = new License().get("type="+license.getType()+" AND tid= "+license.getTid());
			if(pojo==null) 
			{
				license.save();
			}
		}
//		DBManager.closeConnection();
	}
}
